const fs = require('fs');
const path = require('path');
const Router = require('koa-router');

// 默认读取controllers目录下的所有js文件，文件迁移的时候，只需要修改这个地方
const controllersPath = path.join(path.dirname(__dirname), "controllers");


function _addMapping(router, mapping) {
  for (const key in mapping) {      // for in 遍历的是对象的key,或者数组的索引
    if (mapping.hasOwnProperty(key)) {
      const element = mapping[key];
      if (key.startsWith('GET ')) {
        let path = key.substring(4);
        router.get(path, element);
      } else if (key.startsWith('POST ')) {
        let path = key.substring(5);
        router.post(path, element);
      }
    }
  }
}

// 默认添加controllers目录下的所有js文件，dir参数是controllers下的目录
function _addControllers(dir) {
  let jspath = controllersPath;
  if (dir) {
    jspath = path.join(jspath, dir);
  }
  let router = new Router();              // 获取一个路由实例
  let fsPromises = fs.promises;           // node 10.0新增的api
  fsPromises.readdir(jspath).then((files)=>{
    let filesFliter = files.filter((file, index)=>{
      return file.endsWith('.js');
    });
    for (const file of filesFliter) {   // for of 遍历的是可迭代对象的全部值
      // mapping 必须是个对象
      const mapping = require(path.join(jspath, file));
      if (typeof mapping === 'function') {
        throw new TypeError(`${file}.js不能返回函数`);
      }
      _addMapping(router, mapping);
    }
  }, (err)=>{
    // 文件打开失败
  });
  return router.routes();
}

module.exports = {
  addController: _addControllers,
};

